package com.runtime.hongyunuser.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.runtime.hongyunuser.bean.*;
import com.runtime.hongyunuser.mapper.UserMapper;
import com.runtime.hongyunuser.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Users login(Users users) {
        return userMapper.login(users);
    }

    @Override
    public List<Categories> getMenu() {
        return userMapper.getMenu();
    }



    // 对外暴露的分页方法（会被事务代理包裹）
    @Override
    public PageInfo<OrderDTO> getOrderList(Long userId, String orderNumber,
                                           String productNumber, String status,
                                           LocalDate startDate, LocalDate endDate,
                                           Integer pageNum, Integer pageSize) {
        // 内部调用非事务方法
        return this.doGetOrderList(userId, orderNumber, productNumber, status, startDate, endDate, pageNum, pageSize);
    }
    // 真正的分页逻辑（非事务方法）
    private PageInfo<OrderDTO> doGetOrderList(Long userId, String orderNumber,
                                              String productNumber, String status,
                                              LocalDate startDate, LocalDate endDate,
                                              Integer pageNum, Integer pageSize) {
        // 分页必须在非事务环境下执行
        PageHelper.startPage(pageNum, pageSize);
        List<OrderDTO> list = userMapper.getOrderList(userId, orderNumber, productNumber, status, startDate, endDate);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<Useraddresses> selectUserAddresses(Long userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Useraddresses> list = userMapper.selectUserAddresses(userId);
        return new PageInfo<>(list);
    }

    @Override
    public void clearDefaultAddresses(Long userId) {
        userMapper.clearDefaultAddresses(userId); // 不需要返回值检查
    }

    @Override
    public int setDefaultAddress(Long addressId, Long userId) {
        // 1. 清除默认标记（会自动继承接口的事务注解）
        userMapper.clearDefaultAddresses(userId);

        // 2. 设置新默认地址
        int affected = userMapper.setDefaultAddress(addressId, userId);

        // 3. 验证影响行数
        if (affected == 0) {
            // 手动触发回滚（通过抛出非检查异常）
            throw new RuntimeException("地址不存在或更新失败");
        }
        return affected; // 返回影响行数
    }


    @Override
    public List<Regions> getRegionsByParentId(Integer parentId) {
        return userMapper.selectRegionsByParentId(parentId);
    }



    @Override
    public void addUserAddress(Useraddresses useraddresses) {
        // 设置用户ID (当前示例硬编码为1L，实际应从登录信息获取)
        useraddresses.setUserId(1L);

        // 如果是设置为默认地址，先清除其他默认地址
        if (useraddresses.getIsDefault() == 1) {
            userMapper.clearDefaultAddresses(useraddresses.getUserId());
        }

        // 插入新地址
        int affected = userMapper.insertUserAddress(useraddresses);
        if (affected == 0) {
            throw new RuntimeException("添加地址失败");
        }
    }

    @Override
    public void updateUserAddress(Useraddresses useraddresses) {
        // 设置用户ID (当前示例硬编码为1L，实际应从登录信息获取)
        useraddresses.setUserId(1L);

        // 如果是设置为默认地址，先清除其他默认地址
        if (useraddresses.getIsDefault() == 1) {
            userMapper.clearDefaultAddresses(useraddresses.getUserId());
        }

        // 更新地址
        int affected = userMapper.updateUserAddress(useraddresses);
        if (affected == 0) {
            throw new RuntimeException("更新地址失败");
        }
    }

    @Override
    public void deleteUserAddress(Long addressId, Long userId) {
        int affected = userMapper.deleteUserAddress(addressId, userId);
        if (affected == 0) {
            throw new RuntimeException("删除地址失败");
        }
    }


    @Override
    public OrderDTO getOrderDetail(String orderNumber) {
        OrderDTO order = userMapper.getOrderDetail(orderNumber);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        return order;
    }
    @Override
    public List<OrderItemDTO> getOrderItems(String orderNumber) {
        return userMapper.getOrderItems(orderNumber);
    }
    @Override
    public ShippingAddressDTO getOrderShippingAddress(String orderNumber) {
        return userMapper.getOrderShippingAddress(orderNumber);
    }

    @Override
    public List<Useraddresses> selectUserAddress(Long userId) {
        return userMapper.selectUserAddresses(userId);
    }

    @Override
    public int insertOrder(Orders orders) {
        // 1. 插入订单主表
        int affected = userMapper.insertOrder(orders);

        if (affected == 0) {
            throw new RuntimeException("插入订单失败");
        }

        // 2. 插入订单商品
        if (orders.getItems() != null && !orders.getItems().isEmpty()) {
            // 设置订单ID
            orders.getItems().forEach(item -> item.setOrderId(orders.getOrderId()));

            // 批量插入商品
            userMapper.insertOrderItems(orders.getItems());
        }

        return affected;
    }


}
